<?php

namespace Abo\Larasearch\V0\RedisBitMap;

use Elasticsearch\Client;
use Elasticsearch\ClientBuilder;
use Elasticsearch\Common\EmptyLogger;
use Illuminate\Support\ServiceProvider;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

class RedisBitmapProvider extends ServiceProvider
{

    public function __construct( \Illuminate\Contracts\Foundation\Application $app )
    {
        parent::__construct( $app );
    }

    /** ES链接实例绑定 @return void */
    public function bindBuilder()
    {
        $this->app->bind( EsBuilder::class, function ($app) {
            return new EsBuilder(
                $app->make('config')->get('larasearch.elasticsearch'),
                new Grammar(),
                $this->clientBuilder()
            );
        });
    }

    /** ES查询构造器客户端 @return Client */
    protected function clientBuilder(): Client
    {
        $clientBuilder = ClientBuilder::create()
            ->setConnectionPool( $this->app->make( 'config' )->get( 'larasearch.elasticsearch.connection_pool' ) )
            ->setSelector( $this->app->make( 'config' )->get( 'larasearch.elasticsearch.selector' ) )
            ->setHosts( $this->app->make( 'config' )->get( 'larasearch.elasticsearch.hosts' ) );

        if ( $this->app->make( 'config' )->get( 'larasearch.elasticsearch.open_log' ) ) {
            $logger = new Logger( 'elasticsearch' );
            $logger->pushHandler( new StreamHandler( $this->app->make( 'config' )->get( 'larasearch.elasticsearch.log_path' ), Logger::INFO ) );

            $clientBuilder = $clientBuilder->setLogger( $logger );
        }

        return $clientBuilder->build();
    }
}